var promoteCode = getCookie("qyyx_code_sdzfxlsdflv");
$(function () {
	// 响应式布局
	var winWidth = $(window).width();
	$("html").css("fontSize", (winWidth / 640) * 40 + "px");


	// 分享
	// $("#socialShare").socialShare({
	// 	content: '',
	// 	url:'',
	// 	titile:''
	// });
	// $("#shareQQ").on("click",function(){
	// 	$(this).socialShare("tQQ");
	// });



	// 不知道什么鬼
	if($('#details-tab').size()>0) {
		tab("details-tab");
	}

	// 轮播
	// if($('#home_slider').size()>0){
	// 	$('#home_slider').flexslider({
	// 		animation : 'slide',
	// 		controlNav : true,
	// 		directionNav : true,
	// 		animationLoop : true,
	// 		slideshow : false,
	// 		useCSS : false,
	// 		slideshow:true,
	// 		slideshowSpeed: 3000
	// 	});	
	// }

    //	拖动返回按钮
    var tar = '.back-bar';  //按钮id
    if($(tar).size()>0){
        touch.on(tar, 'tap', function(ev){
        	var url=$(this).data('url');
            if(url){
            	window.location.href=url;
			}else{
            	window.history.back(-1);
            }
        });
        touch.on(tar, 'touchstart', function(ev){
            ev.preventDefault();
        });
        //var target = document.getElementById("target");
        var ww = $(window).width();
        var wh = $(window).height();
        var dx,dy;
        var dot_w = $(tar).width(); // 按钮宽度
        var dot_h = $(tar).height(); // 按钮高度
        var pos_x = ww/640*40*0.6; // 按钮初始位置x
        var pos_y = ww/640*40*0.6; // 按钮初始位置y

        touch.on(tar, 'drag', function(ev){
            dx = dx || 0;
            dy = dy || 0;
            var offx = dx + ev.x + "px";
            var offy = dy + ev.y + "px";
            var adsorb = 8; //距离屏幕边缘的间距，会被吸附到边缘
            //检测是否到4个屏幕边缘
            if(parseFloat(offx)+dot_w - pos_x + dot_w >= ww - adsorb){
                offx = ww - dot_w - pos_x + "px";
            }
            if(parseFloat(offx) + pos_x <= adsorb){
                offx = -pos_x + "px";
            }
            if(parseFloat(offy)+2*dot_h >= wh - adsorb){
                offy = wh - dot_h - pos_y + "px";
            }
            if(parseFloat(offy) + pos_y <= adsorb){
                offy = -pos_y + "px";
            }
            this.style.webkitTransform = "translate3d(" + offx + "," + offy + ",0)";


        });

        touch.on(tar, 'dragend', function(ev){
            console.log(ev);
            console.log(ev.x,ev.y);
            // console.log(Math.abs(offx.split('px')[0]) ,Math.abs(offy.split('px')[0]));


            dx += ev.x;
            dy += ev.y;
            //追加移5px偏差
            if (Math.abs(ev.x) < 6 || Math.abs(ev.y)<6 ){
                var url=$(this).data('url');
                if(url){
                    window.location.href=url;
                }else{
                    window.history.back(-1);
                }
            }
        });
    }

	// 轮播
	if($('#rec_slider').size()>0){
		$('#rec_slider').flexslider({
			animation : 'slide',
			controlNav : true,
			directionNav : true,
			animationLoop : true,
			slideshow : false,
			useCSS : false,
			slideshow:true,
			slideshowSpeed: 3500
		});	
	}
	if($('#tab').size()>0){
		tabs.init("tab");	
	}
	if($('.number').size()>0){
		if($("#route-list").length>0){
				var totalp=0;
					$(".route-price").each(function(){
						var price=$(this).find("strong").text();
						totalp=operation.accAdd(totalprice,price);
					});
					$("#totalprice").text(totalp);
					$('input[name=totalPrice]').val(totalp);
				}
				else{
					totalprice(1);
				}
		$(".number").numSpinner({
			min:1,
			onChange:function(evl,value){
				if($("#route-list").length>0){
					routetotalprice();
				}
				else{
					totalprice(value);
				}
			}
		});	
	}
	$("#mask").height($(document).height());
	$(".tips-wrapper").css("min-height",$(window).height());
	
	// pop tips
	$('.tips a').on('click',function (){
		$('.mask,.tips').hide();
	});
});

var tabs={
	init:function(divid){
		$("#"+divid).find("a").click(function(e){
			var itmeId=$(this).attr("href");
			if(itmeId.substr(0,1)=="#"){
				e.preventDefault();
			}
			$(itmeId).addClass('active').siblings().removeClass("active");
			$(this).parent().addClass('active').siblings().removeClass("active");
		});
	}
};

/**
 *计算购买支付价格
 * @param {*购买数量} num 
 * @param {*优惠券满减限制} fullCat 
 * @param {*优惠券类型} couponType
 * @param {*优惠券券值} couponValue
 */
function totalprice(num){
	var price=$("#price").text();
	var payPrice = $('.payPrice');
	var couponInfo = $('#couponInfo');
	var couponHandlePrice = $('.couponHandlePrice');
	var couponType, fullCat, couponValue;

	if (couponInfo){
		couponType = couponInfo.data('T');
		fullCat = couponInfo.data('F');
		couponValue = couponInfo.data('V');
	}

	var _totalPrice = parseFloat(operation.accMul(price, num).toFixed(2));

	var _handledPrice = '';
	$("#totalprice").text(_totalPrice);
	$('#cost-dialog .cost-dialog-explian strong').text(_totalPrice);
	if (couponType&&couponValue&&(+_totalPrice >= fullCat)){

        var handlePrice='';
		if(couponClist.length>0){
            _handledPrice=_totalPrice;
            couponClist.forEach(function (val,i) {
                _handledPrice = (+couponType)
                    ? ( _handledPrice * ((+val.data.V) / 10))
                    : ( _handledPrice - (+val.data.V) );
                (+couponType)
                    ? handlePrice += '*' + ( (+val.data.V) / 10)
                    : handlePrice += '-' + val.data.V;

            });
            // _handledPrice = (+couponType)
            //     ? ( _totalPrice * ((+couponValue) / 10)).toFixed(2)
            //     : ( _totalPrice - (+couponValue) ).toFixed(2);
		}
        console.log(handlePrice);
        _handledPrice=_handledPrice? _handledPrice.toFixed(2):'';
        if(module==='shop'){
			//加上邮费
            _handledPrice= ( operation.accAdd( _handledPrice, $('#express_price').find('i').text()||0 )).toFixed(2);
            handlePrice=handlePrice+  ( $('#express_price').find('i').text() ? '+'+ $('#express_price').find('i').text() : '');
        }
		payPrice.html(_handledPrice<0.01?0.01:_handledPrice);

		// var handlePrice='';
        // couponInfo.data('T') === '0'
        //     ? handlePrice = '- ' + couponInfo.data('V') + ' ='
        //     : handlePrice = '* ' + (couponInfo.data('V') / 10) + ' =';
        couponHandlePrice.html( handlePrice+'=' );

		$('input[name=totalPrice]').val(_handledPrice<0.01?0.01:_handledPrice);

		return 1; //优惠券有效处理了价格
	} else {
		$('input[name=totalPrice]').val(_totalPrice);
		payPrice.html('');
        couponHandlePrice.html('');
        if(module==='shop' ){
            console.log(1);
            if(couponClist.length===0 || (+_totalPrice < fullCat) ){
                if( $('#express_price').find('i').text() ){
                    //加上邮费
                    $('.couponHandlePrice').html( '+' + $('#express_price').find('i').text() +'=');
                    $('.payPrice').html(
                        (
                            operation.accAdd( $('#totalprice').text(), $('#express_price').find('i').text() )
                        ).toFixed(2)
                    );
                }
			}
        }
		return 0; //没有用优惠券处理价格
	}
}

function routetotalprice(){
	var totalprice=0;
	$(".number").each(function(){
		var val=$(this).val();
		var price=$(this).parent().next().find("strong").text();
		totalprice=operation.accAdd(totalprice,operation.accMul(val,price));
	});
	$("#totalprice").text(totalprice);
	$('input[name=totalPrice]').val(totalprice);
}

//四则运算
var operation={
	accMul:function(arg1,arg2){
		var m=0,s1=arg1.toString(),s2=arg2.toString();
		try{m+=s1.split(".")[1].length}catch(e){}
		try{m+=s2.split(".")[1].length}catch(e){}
		return Number(s1.replace(".",""))*Number(s2.replace(".",""))/Math.pow(10,m);
	},
	accDiv:function(arg1,arg2){
		var t1=0,t2=0,r1,r2;
	    try{t1=arg1.toString().split(".")[1].length}catch(e){}
	    try{t2=arg2.toString().split(".")[1].length}catch(e){}
	    with(Math){
	        r1=Number(arg1.toString().replace(".",""));
	        r2=Number(arg2.toString().replace(".",""));
	        return (r1/r2)*pow(10,t2-t1);
	    }
	},
	accAdd:function(arg1, arg2){
        var r1, r2, m, c;
        try { r1 = arg1.toString().split(".")[1].length } catch (e) { r1 = 0 }
        try { r2 = arg2.toString().split(".")[1].length } catch (e) { r2 = 0 }
        c = Math.abs(r1 - r2);
        m = Math.pow(10, Math.max(r1, r2));
        if (c > 0) {
            var cm = Math.pow(10, c);
            if (r1 > r2) {
                arg1 = Number(arg1.toString().replace(".", ""));
                arg2 = Number(arg2.toString().replace(".", "")) * cm;
            }
            else {
                arg1 = Number(arg1.toString().replace(".", "")) * cm;
                arg2 = Number(arg2.toString().replace(".", ""));
            }
        }
        else {
            arg1 = Number(arg1.toString().replace(".", ""));
            arg2 = Number(arg2.toString().replace(".", ""));
        }
        return (arg1 + arg2) / m

        // var r1,r2,m;
	    // try{r1=arg1.toString().split(".")[1].length;}catch(e){r1=0;}
	    // try{r2=arg2.toString().split(".")[1].length;}catch(e){r2=0;}
	    // m=Math.pow(10,Math.max(r1,r2));
	    // return (arg1*m+arg2*m)/m;
	},
	accSub:function(arg1,arg2){
		var r1,r2,m,n;
	     try{
	         r1=arg1.toString().split(".")[1].length;
	         }catch(e){
	             r1=0;
	             }
	     try{
	         r2=arg2.toString().split(".")[1].length;
	         }catch(e){
	             r2=0;
	             }
	     m=Math.pow(10,Math.max(r1,r2));
	     //last modify by deeka
	     //动态控制精度长度
	     n=(r1>=r2)?r1:r2;
	     return ((arg2*m-arg1*m)/m).toFixed(n);
	}
};
function tab(id){
	var touchObj=$("#"+id).find("a");
	 $("#tab-panel").find(".details-tab-item:eq(0)").css("height","auto");
	 touch.on(touchObj,'tap',function(){
		 var index=$(this).parent().index(),divid=$(this).data("div");
		 touchObj.removeClass("active");
		 $(this).addClass("active");
		 $("#tab-panel").css("margin-left",-(Math.round(index * 10000)/100).toFixed(2) + '%').find(".details-tab-item").removeAttr("style");
		 $("#"+divid).css("height","auto");
	 });
 }

//  业务类型
function getModule(module){
	var title="";
	switch (module){
		case "ticket":
			title="景区";
			break;
		case "hotel":
			title="酒店";
			break;
		case "route":
			title="跟团游";
			break;
		case "line":
			title="自由行";
			break;
		case "cate":
			title="餐饮";
			break;
		case "goods":
			title="商品";
			break;
		case "raiders":
			title="攻略";
			break;
		case "guide":
			title="导游";
			break;
	}
	return title;
}

//
function maxNumber(num,max) {
	var n=num || 0;
	return n>max?(max+'+'):n
}


// 业务类型图标
function getIcon(m){
	switch (m){
		case 'ticket':
			return '<span class="order-info"><i class="font-icon icon-iconfont-menpiao"></i>' +
                   '<em>景区';
			break;
		case 'hotel':
			return '<span class="order-info"><i class="font-icon icon-iconfont-jiudian"></i>' +
                   '<em>酒店';
			break;
		case 'combo':
			return '<span class="order-info"><i class="font-icon icon-iconfont-ziyouxing"></i>' +
                   '<em>套票';
			break;
        case 'zyx':
            return '<span class="order-info"><i class="font-icon icon-iconfont-ziyouxing"></i>' +
                '<em>自由行';
            break;
        case 'route':
            return '<span class="order-info"><i class="add-icon addicon-iconfont-route"></i>' +
                '<em>跟团游';
            break;
        case 'guide':
            return '<span class="order-info"><i class="add-icon addicon-iconfont-guide"></i>' +
                '<em>导游';
            break;
		case 'shop':
			return '<span class="order-info"><i class="font-icon icon-iconfont-shouji3"></i>' +
                   '<em>购物';
			break;
		case 'repast':
			return '<span class="order-info"><i class="font-icon icon-iconfont-canting"></i>' +
                   '<em>美食';
			break;
        case 'amuse':
            return '<span class="order-info"><i class="font-icon icon-iconfont-amuse"></i>' +
                '<em>娱乐';
            break;
        case 'vehicle':
            return '<span class="order-info"><i class="add-icon addicon-iconfont-zuche"></i>' +
                '<em>约车';
            break;
		case 'traffic':
			return '<span class="order-info"><i class="font-icon icon-iconfont-amuse"></i>' +
                   '<em>交通';
			break;
	}
}

//  导游等级
function guideLevel(level){
	switch (level){
		case '铜牌':
			return '<i class="icon-guide-level3"></i>';
			break;
		case '银牌':
			return '<i class="icon-guide-level2"></i>';
			break;
		case '金牌':
			return '<i class="icon-guide-level"></i>';
			break;
	}
}

//  床型
function isBed(bed){
	switch (bed){
        case '0':
            str="大床";
            break;
        case '1':
            str="双床";
            break;
        case '2':
            str="榻榻米";
            break;
        case '3':
            str="三人床";
            break;
        case '4':
            str="套房";
            break;
        case '5':
            str="多床";
            break;
	}
}

//  早餐
function isBreakfast(Breakfast){
	switch (Breakfast){
		case 0:
			return '单早';
			break;
		case 1:
			return '单早';
			break;
		case 2:
			return '单早';
			break;
	}
}

// 检测终端
function ispc(){
	 var flag=true;
	 var system = {
		 win: false,
		 mac: false,
		 xll: false,
		 ipad:false
	 };
	 //检测平台
	 var p = navigator.platform;
	 system.win = p.indexOf("Win") == 0;
	 system.mac = p.indexOf("Mac") == 0;
	 system.x11 = (p == "X11") || (p.indexOf("Linux") == 0);
	 system.ipad = (navigator.userAgent.match(/iPad/i) != null)?true:false;
	 //跳转语句，如果是手机访问就自动跳转到wap.baidu.com页面
	 if (system.win || system.mac || system.xll||system.ipad) {
		 flag=true;
	 } else {
		 flag=false;
	 }
	 return flag;
 }

//  跳转错误页面
function error(){
	window.location.href = '/error';
}

// 订单状态
function payStatus(s,m,o){
    s = typeof s === 'string' ? parseInt(s) : s;
	switch (s){
		case 0:
			return '待支付'; break;
		case 1:
			return m==='goods'?'待发货': ( o=='1'?'待确认':'已付款'); break;
		case 2:
			return '交易成功'; break;
		case 3:
			return '已退款'; break;
		case 4:
			return '交易取消'; break;
		case 5:
			return '已退款'; break;
		case 6:
			return '已发货'; break;
		case 7:
			return '已过期'; break;
		case 8:
			return '待确认'; break;
		case 9:
			return '已确认'; break;
		case 10:
			return '确认失败'; break;
	}
}

//约车订单状态
function carPayStatus(s) {
    s = typeof s === 'string' ? parseInt(s) : s;
    switch (s) {
        case 0:
            return '待接单';
            break;
        case 1:
            return '已接单';
            break;
        case 2:
            return '订单成功';
            break;
        case 3:
            return '订单完结';
            break;
        case 4:
            return '订单取消';
            break;
        case 5:
            return '已退款';
            break;
        case 6:
            return '退款中';
            break;
        case 7:
            return '已支付';
            break;
        case 8:
            return '待支付';
            break;
    }
}
//约车服务种类
function carOrderType(s) {
    s = typeof s === 'string' ? parseInt(s) : s;
    switch (s) {
        case 1:
            return '专快车';
            break;
        case 2:
            return '接机';
            break;
        case 3:
            return '送机';
            break;
        case 4:
            return '接站';
            break;
        case 5:
            return '送站';
            break;
    }
}
function carType(s) {
    s = typeof s === 'string' ? parseInt(s) : s;
    switch (s) {
        case 1:
            return '出租车';
            break;
        case 2:
            return '新能源';
            break;
        case 3:
            return '舒适型';
            break;
        case 4:
            return '豪华型';
            break;
        case 5:
            return '商务型';
            break;
    }
}
/**
 * 去除日历数据中的时间，保留日期
 * @param date (eg:2017-10-17 12:05:05)
 */
function dealTimeDate(date){
	var dateArray = date.split(' ');
	return dateArray[0];
}

/**
 * 订单使用状态
 * @param t
 * @returns {*}
 */
function useStatus(t) {
	switch (t){
		case '0':
			return '未使用'; break;
		case '1':
			return '使用中'; break;
		case '2':
			return '已使用'; break;
		default:break;

	}
}


//获取cookie
function getCookie(name){
    var arr,reg=new RegExp("(^| )"+name+"=([^;]*)(;|$)");
    if(arr=document.cookie.match(reg))
        return unescape(arr[2]);
    else
        return null;
}
Date.prototype.Format = function (fmt) { //author: meizz
    fmt = fmt || 'yyyy-MM-dd';
    var o = {
        "M+": this.getMonth() + 1,                 //月份
        "d+": this.getDate(),                    //日
        "h+": this.getHours(),                   //小时
        "m+": this.getMinutes(),                 //分
        "s+": this.getSeconds(),                 //秒
        "q+": Math.floor((this.getMonth() + 3) / 3), //季度
        "S": this.getMilliseconds()             //毫秒
    };
    if (/(y+)/.test(fmt))
        fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
    for (var k in o)
        if (new RegExp("(" + k + ")").test(fmt))
            fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
    return fmt;
};

Date.prototype.Add = function (interval, number) {
    /*
  　　* 功能:实现VBScript的DateAdd功能.
  　　* 参数:interval,字符串表达式，表示要添加的时间间隔.
  　　* 参数:number,数值表达式，表示要添加的时间间隔的个数.
  　　* 参数:date,时间对象.
  　　* 返回:新的时间对象.
  　　* var now = new Date();
  　　* var newDate = DateAdd( "d ",5,now);
  　　*--------------- DateAdd(interval,number,date) -----------------
  　　*/
    var date = this;
    switch (interval) {
        case "y":
            date.setFullYear(date.getFullYear() + number);
            return date;
            break;
        case "q":
            date.setMonth(date.getMonth() + number * 3);
            return date;
            break;
        case "M":
            date.setDate('01');
            date.setMonth(date.getMonth() + number);
            return date;
            break;
        case "w":
            date.setDate(date.getDate() + number * 7);
            return date;
            break;
        case "d":
            date.setDate(date.getDate() + number);
            return date;
            break;
        case "h":
            date.setHours(date.getHours() + number);
            return date;
            break;
        case "m":
            date.setMinutes(date.getMinutes() + number);
            return date;
            break;
        case "s":
            date.setSeconds(date.getSeconds() + number);
            return date;
            break;
        default:
            date.setDate(date.getDate() + number);
            return date;
            break;
    }
};


//获取地址栏参数
function GetQueryString(name) {
    var reg = new RegExp("(^|&)"+ name +"=([^&]*)(&|$)");
    var r = window.location.search.substr(1).match(reg);
    if(r!=null)return  unescape(r[2]); return null;
}

//时间转换
function bdate(time) {
    var s = time.replace(/-/g, "/");
    return (new Date(s)).getTime()
}
function ndate(time){
    var date = new Date(time);
    var year = date.getFullYear();
    var month = date.getMonth()+1;
    var day = date.getDate();
    var hour=date.getHours();
    var min=date.getMinutes();
    var s=date.getSeconds();
    return [year,p(month),p(day)].join('.')+' '+[p(hour),p(min),p(s)].join(':');
}
function p(s) {
    return s < 10 ? '0' + s : s;
}
function thistime(s) {
    var da = new Date().Add('m',s||0);
    var year = da.getFullYear();
    var month = da.getMonth() + 1;
    var day = da.getDate();
    var s = da.getHours();
    var f = da.getMinutes();
    var m = da.getSeconds();
    var _time = [year, p(month), p(day)].join('-') + " " + p(s) + ":" + p(f) ; //+ ":" + p(m)
    return _time
}
